/********************************************************************
* im_extras.js
*
* This file contains functions related to the intermap extra features
* ie the ones the user can call via the buttons below the bigger map.
*


 requires:
    clearNode(node)
    extractScripts() // from prototype.js
    getIMServiceURL(service)
    imc_addServices(url, services, type, im_servicesAdded);
	im_buildLayerList(req); // rebuild layers' list
	
	im_deleteClientMarker(markerid);
	im_retitleClientMarker(markerid, title)
		
	im_extra_drivingMap : Intermap; must be set
	
    requires a div with id = "im_whiteboard"
 
********************************************************************/


/** set this var as the main Intermap object */
var im_extra_drivingMap;

// set this object to a function that will be called whenever a style has been set. 
//var im_extra_afterStyleSet = function() { alert("im_extra_afterStyleSet in file im_extras.js is not set");};

var im_extra_afterWmcSet = function() { alert("im_extra_afterWmcSet in file im_extras.js is not set");};
var im_extra_afterLayerUpdated = function() { alert("im_extra_afterLayerUpdated in file im_extras.js is not set");};


/********************************************************************
*** LAYERS
********************************************************************/
/*
## Called by the bottom toolbar
## Shows a list of configured map servers
*/
function im_addLayer()
{
    // setup WB
    clearNode('im_whiteboard');    
    var WB = $('im_whiteboard');

    var wbtitle = im_createWBTitle(i18n('addLayer'));
    WB.appendChild(wbtitle);

    var closer = im_getWBCloser();
    WB.appendChild(closer);
    Event.observe(closer, 'click', im_closeWhiteBoard);

    // fill contents
    var div = document.createElement('div'); // main box
    div.id = "im_serverList";
    div.className = 'im_wbcontent';
    WB.appendChild(div);
   
    var myAjax = new Ajax.Updater (
		'im_serverList',    
    	getIMServiceURL('mapServers.listServers.embedded'), 
    	{
    		method: 'get',    		    	
    		onFailure: im_load_error
    	}
    );
}

/*
## Called when a known map server has been selected
*/
function im_mapServerSelected(id, name, refreshCache)
{
	var im = $('im_serverList');
	clearNode(im);
	
	var t1 = document.createElement("p");
	t1.innerHTML = i18n("wait");
	im.appendChild(t1);
	
	var t2 = document.createElement("p");
	t2.innerHTML = i18n("loadingFrom") + " " + name;	
	im.appendChild(t2);

	imc_loadServerServices(id, refreshCache, im_servicesLoaded, "im_servicesSelected();");
}

function imc_loadServerServices(id, refreshCache, callback, jscallback)
{
	var pars = 'mapserver='+id  				
                +"&jscallback="+encodeURIComponent(jscallback)
                +"&refreshCache="+refreshCache;

	var myAjax = new Ajax.Request (
		getIMServiceURL('mapServers.getServices.embedded'), 
		{
			method: 'get',
			parameters: pars,
			onSuccess: callback,
			onFailure: im_load_error
		}
	);
}

/*
## Called when the URL of an unknown map server has been given
*/
function im_mapServerURL(url, refreshCache)
{
	var im = $('im_serverList');
	clearNode(im);

	var t1 = document.createElement("p");
	t1.innerHTML = i18n("wait");
	im.appendChild(t1);

	var t2 = document.createElement("p");
	t2.innerHTML = i18n("loadingFromWMS");	
	im.appendChild(t2);

	imc_loadURLServices(url, refreshCache, -2, im_servicesLoaded, "im_servicesSelected();" );
}

function imc_loadURLServices(url, refreshCache, type, callback, jscallback)
{
	var pars = 'mapserver='+type
	                +"&url="+encodeURIComponent(url)
	                +"&jscallback="+encodeURIComponent(jscallback)
	                +"&refreshCache="+refreshCache;
	
	var myAjax = new Ajax.Request (
		getIMServiceURL('mapServers.getServices.embedded'), 
		{
			method: 'get',
			parameters: pars,
			onSuccess: callback,
			onFailure: im_load_error
		}
	);
}

function im_servicesLoaded(req)
{
	// Dynamically generate content
	var im = $('im_serverList');
	im.innerHTML =req.responseText;
	var reqScripts = req.responseText.extractScripts();
	// Only evaluate the first script
	if (reqScripts.length > 0)
		eval(reqScripts[0]);  
}

/*
## Called by the ok button generated by service mapServers.getServices.embedded
*/
function im_servicesSelected()
{
	var im = $('im_serverList');
	
	// next two elements are created by the mapServers.getServices.embedded service
	var url   = $('im_addlayer_serverurl').value;
	var type = $('im_addlayer_type').value;
	
	var services = new Array();
	//var query = "url="+url+"&type="+type;
	
	var lilist = im.getElementsByTagName("input");
			
	$A(lilist).each(
	    function (input)
	    {
	        var value = input.value;
	        var checked = input.checked;
	        
	        if(checked)
	        {
	            services.push(value);
	            //query += "&service="+value;	        
	        }
	    }
	);
	
	im_extra_drivingMap.setStatus('busy');
	imc_addServices(url, services, type, im_servicesAdded);	
}

function im_servicesAdded(req)
{
	var im = $('im_serverList');
	clearNode(im);
	
	var t1 = document.createElement("p");
	t1.innerHTML = i18n("layersAdded");
	im.appendChild(t1);
	
	im_buildLayerList(req); // rebuild layers' list
	
	im_extra_afterLayerUpdated();			
}

/********************************************************************
*** PDF
********************************************************************/
/*
## Called by the bottom toolbar
*/
function im_openPDFform()
{
	// setup WB
	clearNode('im_whiteboard');    
	var WB = $('im_whiteboard');
	
	var wbtitle = im_createWBTitle(i18n('exportAsPDF')); 
	WB.appendChild(wbtitle);
	
	var closer = im_getWBCloser();
	WB.appendChild(closer);
	Event.observe(closer, 'click', im_closeWhiteBoard);
	
	var div = document.createElement('div'); // main box
	div.id = "im_createPDF";
	div.className = 'im_wbcontent';
	WB.appendChild(div);
	
	var myAjax = new Ajax.Updater (
		'im_createPDF',    
		getIMServiceURL('static.form.pdf'), 
		{
			method: 'get',    		    	
			onFailure: im_load_error
		}
	);

}

function im_requestPDF()
{
	var orient = $('pdf_orientation').value;
	var psize = $('pdf_pagesize').value;

	var ptitle = $('pdf_title').value;
	var pcopy = $('pdf_copyright').value;
	
	var bllist = $('pdf_layerlist').checked;
	var bdetails = $('pdf_details').checked;
	var bbbox = $('pdf_boundingbox').checked;
	var bscale = $('pdf_scalebar').checked;
	var barrow = $('pdf_arrow').checked;
	
	var pars = "orientation="+orient+
		"&pagesize="+psize+
		"&"+ im_extra_drivingMap.getURLbbox();
		
	if(ptitle)
		pars += "&title="+ encodeURIComponent(ptitle);
	if(pcopy)
		pars += "&copyright="+ encodeURIComponent(pcopy);


	if(bllist)
		pars += "&layerlist=on";
	
	if(bdetails)
		pars += "&details=on";
	
	if(bbbox)
		pars += "&boundingbox=on";

	if(bscale)
		pars += "&scalebar=on";

	if(barrow)
		pars += "&arrow=on";

	$('im_requestingpdf').show();   
	$('im_requestpdf').hide();
	$('im_builtpdf').hide();
	
	var myAjax = new Ajax.Request (
		getIMServiceURL('create.pdf'), 
		{
			method: 'get',
			parameters: pars,
			onSuccess: im_openPDF,
			onFailure: im_load_error
		}
	);
    
}

function im_openPDF(req)
{
    var url = req.responseXML.documentElement.getElementsByTagName('url')[0].firstChild.nodeValue;

    window.open(url);

    $('im_requestpdf').show();
    $('im_requestingpdf').hide();   
    $('im_builtpdf').show();
}

/********************************************************************
*** WMC
********************************************************************/
/**
 * Called by the bottom toolbar
 * @param {String} type optional - may be 'mail' or 'upload'
 */
function im_openWMCform(type)
{
	// setup WB
	clearNode('im_whiteboard');    
	var WB = $('im_whiteboard');

	var i18nkey = "wmctitle";
	if(type)
		i18nkey += type;
	
	var wbtitle = im_createWBTitle(i18n(i18nkey)); 
	WB.appendChild(wbtitle);
	
	var closer = im_getWBCloser();
	WB.appendChild(closer);
	Event.observe(closer, 'click', im_closeWhiteBoard);
	
	var div = document.createElement('div'); // main box
	div.id = "im_wmcmenu";
	div.className = 'im_wbcontent';
	WB.appendChild(div);
	
	var pars="&width=" + im_extra_drivingMap.width +         
		    "&height=" + im_extra_drivingMap.height;
	if(type)			         
		pars += "&type="+type;
		
	var myAjax = new Ajax.Updater (
		'im_wmcmenu',    
		getIMServiceURL('wmc.form'), 
		{
			method: 'get',    		    	
			parameters: pars,
			onFailure: im_load_error
		}
	);

}

/**
## Download WMC context. This is a one-shot operation.
*/
function im_downloadWMC()
{
    var pars= "width=" + im_extra_drivingMap.width +          
                    "&height=" + im_extra_drivingMap.height;        

    window.open(getIMServiceURL('context.cml') + '?'+pars);
}

/**
## Upload a context saved in a local file
## Context can be merged to current layers, or can completely replace them according to the parameter bClearLayers
*/
function im_uploadWMC(bClearLayers)
{
    var form = $('im_fuploadwmc');
    form.action=getIMServiceURL('wmc.uploadContext');
    $('im_fup_clearLayers').value= bClearLayers? 'true' : 'false';
    
    return AIM.submit(form, 
        {
            'onStart' : function() 
            {
                im_extra_drivingMap.setStatus('busy');
                im_wmc_showMessage("upload", "start");
                return true;
            }, 
            'onComplete' : function(domdoc) 
            {
                im_extra_drivingMap.setStatus('idle');
                var resp = domdoc.documentElement;
                if(resp.tagName == "error")
                {
                    var msg = resp.getElementsByTagName('message')[0].firstChild.nodeValue;
                    im_wmc_showMessage("upload", "error", msg);                
                }
                else
                {                
                    im_wmc_showMessage("upload", "ok");                
                    imc_reloadLayers();
                    
					im_extra_afterWmcSet(resp);
                }
            }                    
        });
}

// Send WMC as e-mail
function im_sendWMC()
{
	var title = $('wmc_title').value;
	var from = $('wmc_mailfrom').value;
	var to = $('wmc_mailto').value;

            if(!title || !from || !to)
            {
                alert("Please fill in information"); //FIXME i18n
                return;
            }
	
	pars="wmc_title=" + encodeURIComponent(title)
		+"&wmc_mailfrom=" + encodeURIComponent(from)
		+"&wmc_mailto=" + encodeURIComponent(to)
		+"&width=" + im_extra_drivingMap.width    // WMC stuff     
		+"&height=" + im_extra_drivingMap.height; // WMC stuff    

	im_wmc_showMessage("mail", "start");

	var myAjax = new Ajax.Request (
		getIMServiceURL('wmc.mailContext'), 
		{
			method: 'post',
			parameters: pars,
			onSuccess: function(req)
			{
			    var resp = req.responseXML.documentElement;
				if(resp.tagName == "error")
				{
					var msg = resp.getElementsByTagName('message')[0].firstChild.nodeValue;
					im_wmc_showMessage("mail", "error", msg);                
				}
				else
				{                
					im_wmc_showMessage("mail", "ok");
				}
			},
			onFailure: function(req)
			{
				im_wmc_showMessage("mail", "error");			
			}
		}
	);
    
}

function im_openWMC(req)
{
    var url = req.responseXML.documentElement.getElementsByTagName('url')[0].firstChild.nodeValue;

    window.open(url);

    $('im_requestpdf').show();
    $('im_requestingpdf').hide();   
    $('im_builtpdf').show();
}


/*function im_wmc_showMessage(task, status, more)
{
    $('im_wmc_form').hide();
    
    $('im_wmc_msg_'+task+"_start").hide();
    $('im_wmc_msg_'+task+"_ok").hide();
    $('im_wmc_msg_'+task+"_error").hide();
    
    $('im_wmc_msg_'+task+"_"+status).show();
    
    if(more)
    {
        var div = document.createElement('div');
        div.innerHTML = more;
        $('im_wmc_msg_'+task+"_"+status).appendChild(div);        
    }
}
*/

function im_wmc_showMessage(task, status, more)
{
    im_showMessage('wmc', task, status, more);
}

function im_showMessage(context, task, status, more)
{
    $('im_'+context+'_form').hide();
    
    $('im_'+context+'_msg_'+task+"_start").hide();
    $('im_'+context+'_msg_'+task+"_ok").hide();
    $('im_'+context+'_msg_'+task+"_error").hide();
    
    $('im_'+context+'_msg_'+task+"_"+status).show();
    
    if(more)
    {
        var div = document.createElement('div');
        div.innerHTML = more;
        $('im_'+context+'_msg_'+task+"_"+status).appendChild(div);        
    }
}

/********************************************************************
*** Markers
********************************************************************/
/**
 * Called by the bottom toolbar (id not set).
*  Called from user interaction, clicking on a marker on the map (id set).
*/
function im_markerList(id)
{
	// setup WB
	clearNode('im_whiteboard');    
	var WB = $('im_whiteboard');

	var wbtitle = im_createWBTitle(i18n("markerlisttitle")); 
	WB.appendChild(wbtitle);
	
	var closer = im_getWBCloser();
	WB.appendChild(closer);
	Event.observe(closer, 'click', im_closeWhiteBoard);
	
	var div = document.createElement('div'); // main box
	div.id = "im_markerlist";
	div.className = 'im_wbcontent';
	WB.appendChild(div);
			
	var par="";
	if(id)
	{
		par = "id=" + id; 		
	}
			
	var myAjax = new Ajax.Updater (
		'im_markerlist',    
		getIMServiceURL('marker.present'), 
		{
			method: 'get',
			parameters: par,    		    	
			onFailure: im_load_error
		}
	);
	
}

/**
 * Called from user interaction in markers' list. 
 * See im_get-markers.xsl
 * 
 * @param {Object} id The marker's id
 */
function im_selectMarkerFromList(id) 
{
	var myAjax = new Ajax.Updater (
		'im_markerlist',    
		getIMServiceURL('marker.present'), 
		{
			method: 'get',
			parameters: 'id='+id,    		    	
			onFailure: im_load_error
		}
	);
}

function im_updateMarker(id)
{
	var title = $('marker_title_'+id).value;
	var desc  = $('marker_desc_'+id).value;
	
	var pars = "id=" + id
				+"&title=" + encodeURIComponent(title)
	 			+ "&desc=" + encodeURIComponent(desc);

	im_marker_showMessage("update", "start");                

	var myAjax = new Ajax.Request (
		getIMServiceURL('marker.update'), 
		{
			method: 'post',
			parameters: pars,
			onSuccess: function(req)
			{
			    var resp = req.responseXML.documentElement;
				if(resp.tagName == "error")
				{
					var msg = resp.getElementsByTagName('message')[0].firstChild.nodeValue;
					im_marker_showMessage("update", "error", msg);                
				}
				else
				{   
					im_marker_showMessage("update", "ok");
					im_retitleClientMarker(id, title)
				}
			},
			onFailure: function(req)
			{
				im_marker_showMessage("update", "error");			
			}
		}
	);
	
}

function im_deleteMarker(id)
{
	im_marker_showMessage("delete", "start");                

	var myAjax = new Ajax.Request (
		getIMServiceURL('marker.delete'), 
		{
			method: 'post',
			parameters: {id: id},
			onSuccess: function(req)
			{
			    var resp = req.responseXML.documentElement;
				if(resp.tagName == "error")
				{
					var msg = resp.getElementsByTagName('message')[0].firstChild.nodeValue;
					im_marker_showMessage("delete", "error", msg);                
				}
				else
				{                
					im_marker_showMessage("delete", "ok");
					im_deleteClientMarker(id);
				}
			},
			onFailure: function(req)
			{
				im_marker_showMessage("delete", "error");			
			}
		}
	);
	
}

function im_marker_showMessage(task, status, more)
{
    im_showMessage('marker', task, status, more);
}


/********************************************************************
*** Export image
********************************************************************/
/*
## Called by the bottom toolbar
*/
function im_openPictureForm()
{
    clearNode('im_whiteboard');

    var div = document.createElement('div');
    div.id = "im_createPic";
    $('im_whiteboard').appendChild(div);

    var wbtitle = im_createWBTitle("Export this map as image"); //FIXME i18n
    div.appendChild(wbtitle);

    var closer = im_getWBCloser();
    div.appendChild(closer);
    Event.observe(closer, 'click', im_closeWhiteBoard);

    var h1 = document.createElement('h1');
    h1.innerHTML = "TODO" ; //FIXME i18n 
    div.appendChild(h1);

}


/********************************************************************
*** Layer metadata
***
*** This feature is not triggered from the bottom toolsbar, but by the "show metadata" button on every layer.
*** We'll use the sub-map area to display these info.
***
********************************************************************/

function im_showLayerMD(id)
{
    // setup WB
    clearNode('im_whiteboard');    
    var WB = $('im_whiteboard');

    var wbtitle = im_createWBTitle(i18n('showLayerMD')); 
    WB.appendChild(wbtitle);

    var closer = im_getWBCloser();
    WB.appendChild(closer);
    Event.observe(closer, 'click', im_closeWhiteBoard);

    // fill contents
    var div = document.createElement('div'); // main box
    div.id = "im_showLayerMD";
    div.className = 'im_wbcontent';
    WB.appendChild(div);
   
    var myAjax = new Ajax.Request(    
    	getIMServiceURL('map.layers.getInfo'), 
    	{
    		method: 'get',    
    		parameters: 'id='+id,
    		onSuccess: function(req)
    		{
				if(req.responseXML && req.responseXML.documentElement.tagName == "error")
				{
					var resp = req.responseXML.documentElement;
					var msg = resp.getElementsByTagName('message')[0].firstChild.nodeValue;
					div.innerHTML = msg;
					return;
				}
				else
				{
					div.innerHTML = req.responseText; 
				}
    		},
    		onFailure: function(req)
    		{
				div.innerHTML = i18n('genericError');     		
    		}
    	}
    );    
}

/********************************************************************
*** Layer styles
***
*** This feature is not triggered from the bottom toolsbar, but by the "show styles" button on every layer which has selectable styles..
*** We'll use the sub-map area to display these info.
***
********************************************************************/

function im_showStyles(id)
{
    // setup WB
    clearNode('im_whiteboard');    
    var WB = $('im_whiteboard');

    var wbtitle = im_createWBTitle(i18n('titleShowStyles')); 
    WB.appendChild(wbtitle);

    var closer = im_getWBCloser();
    WB.appendChild(closer);
    Event.observe(closer, 'click', im_closeWhiteBoard);

    // fill contents
    var div = document.createElement('div'); // main box
    div.id = "im_showstyles";
    div.className = 'im_wbcontent';
    WB.appendChild(div);
      
    var myAjax = new Ajax.Request(    
    	getIMServiceURL('map.layers.getStyles'), 
    	{
    		method: 'get',    
    		parameters: 'id='+id,
    		onSuccess: function(req)
    		{
				if(req.responseXML && req.responseXML.documentElement && req.responseXML.documentElement.tagName == "error")
				{
					var resp = req.responseXML.documentElement;
					var msg = resp.getElementsByTagName('message')[0].firstChild.nodeValue;
					div.innerHTML = msg;
					return;
				}
				else
				{
					div.innerHTML = req.responseText; 
				}
    		},
    		onFailure: function(req)
    		{
    			div.innerHTML = i18n('genericError');     		
    		}
    	}
    );    
}

/**
## Called by a button in the layers.getStyles output
*/
function im_setStyle(layerid)
{
    // retrieve selected style
    var style = getRadioValue('styleradio');
    
    var pars = "id="+layerid +
				"&style="+encodeURIComponent(style);
    
    // update user mesg
    im_showMessage('style', 'set', 'start');
    
    // do ajax call
	var myAjax = new Ajax.Request (
		getIMServiceURL('map.layers.setStyle'), 
		{
			method: 'get',
			parameters: pars,
			onSuccess: function(req)
			{
				if(req.responseXML && req.responseXML.documentElement && req.responseXML.documentElement.tagName == "error")
				{
					var resp = req.responseXML.documentElement;
					var msg = resp.getElementsByTagName('message')[0].firstChild.nodeValue;			
					im_showMessage("style", "set", "error", msg);                
				}
				else
				{                
					im_showMessage("style", "set", "ok");
					
					// reload layer list (legend link may have changed)
					im_buildLayerList(req);
					
					// This function is defined at the start of this js file. 
					// It should be overwritten by whoever want to refresh a map
					im_extra_afterLayerUpdated();
				}
			},
			onFailure: function(req)
			{
				im_showMessage("style", "set", "error");
			}
		}
	);       
}

/********************************************************************
*** SUB TOOLBAR UTILITIES
********************************************************************/


function im_createWBTitle(title)
{
    var div = document.createElement('div');
	div.id = "im_wbtitle";
	//var div = Builder.node('div', {id: "im_wbtitle"});
    var h1 = document.createElement('h1');
    h1.innerHTML = title;
    div.appendChild(h1);       

//    Effect.BlindDown('im_whiteboard');

    return div;
}


function im_getWBCloser()
{
	var closer = document.createElement('div');
	closer.id = "im_wbcloser";
//    var closer = Builder.node('div', {id: "im_wbcloser"});
	var img = document.createElement('img');
	img.title = i18n("close");
	img.src = "/intermap/images/close.png";
//    var img = Builder.node('img',
//    {
//        title: "Close", // FIXME i18N
//        src: "/intermap/images/close.png"
//    });
    closer.appendChild(img);
    
    //Event.observe(closer, 'click', im_closeWhiteBoard);
	return closer;
}

function im_closeWhiteBoard()
{
//    Effect.SwitchOff('im_whiteboard');
//    Effect.BlindUp('im_whiteboard');
    clearNode('im_whiteboard');
}
